package problem;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author RunningShrimp
 * @date 2021/6/24  11:28
 * @see <a href="https://leetcode-cn.com/problems/merge-two-sorted-lists">21. 合并两个有序链表</a>
 */
public class MergeTwoSortedLists {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode head = new ListNode(-1);
        ListNode node = head;
        //1. 初始化head用来保存新的节点
        while (l1 != null && l2 != null) {
            if ( l1.val <= l2.val) {
                node.next = l1;
                l1 = l1.next;
            } else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        if (l2 != null) {
            node.next = l2;
        }
        if (l1 != null) {
            node.next = l1;
        }
        return head.next;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
